import { parse } from 'querystring';
import moment from 'moment';
import { message } from 'antd';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg =
  /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

// tableList table列表页默认展示条数
export const tableList = 10;

export const centerMaxHeight = () => {
  const { clientHeight } = document.documentElement;
  const centerHeight = clientHeight - 120 - 112;
  return centerHeight;
};

export const getMqttClientId = () => {
  return `baq_web_v3_${guid()}`;
};

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

//获取token
export const getUserToken = (): string => {
  return sessionStorage.getItem('token') || '';
};

// 获取路由上的参数
export function getQueryString(path: string, name: string) {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
  const r = path.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

export const verification = {
  //二代身份证校验
  idcard:
    /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
  //护照校验
  passport: /^[a-zA-Z][a-zA-Z0-9]{5,11}$/,
  //港澳通行证校验
  HKAndMacaoPass: /^[HMhm]{1}([0-9]{10}|[0-9]{8})$/,
  //台湾往来大陆通行证
  TaiwanPassToChina: /^[0-9]{8}$/,
  //警官证
  policeCard: /^[A-Za-z0-9]{0,8}$/,
  //军官证
  officerCard: /^[A-Za-z0-9\u4e00-\u9fa5]{0,18}$/,
  //电话号码
  contact: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/,
  //数字
  numberReg: /^[0-9]\d*(\.\d+)?$/i,
  // 其他
  other: /^[a-zA-Z0-9\u4E00-\u9FA5]+$/,
};

// 判断是否是管理员/法制人员/民警
// 使用方法：this.checkRole('admin')即可，返回true或false
// @ts-ignore
export const checkRole = (param: string): boolean => {
  const job = {
    police: '200001',
    admin: '200002',
    law: '200003',
  };
  // @ts-ignore
  const user = JSON.parse(sessionStorage.getItem('user'));
  if (user && user.job && user.job.length > 0) {
    const index = user.job.findIndex((value: string) => {
      // 获取当前人员职位在job中的下标
      // @ts-ignore
      return value.code === job[param];
    });
    return index > -1;
  }
};

export const getYearArry = () => {
  let arr = [];
  let year = new Date().getFullYear();
  let i;
  for (i = 0; i < 20; i++) {
    arr.push(year - i);
  }
  return arr;
};
export function fixedZero(val: any) {
  return val * 1 < 10 ? `0${val}` : val;
}
export function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

export function getTimeDistance(type: string) {
  const now = new Date();
  const oneDay = 1000 * 60 * 60 * 24;
  if (type === 'all') {
    return ['', ''];
  }

  if (type === 'today') {
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    return [moment(now), moment(now.getTime() + (oneDay - 1000))];
  }
  if (type === 'week') {
    let day = now.getDay();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    if (day === 0) {
      day = 6;
    } else {
      day -= 1;
    }
    const beginTime = now.getTime() - day * oneDay;
    return [moment(beginTime), moment(now.getTime())];
  }
  if (type === 'month') {
    const year = now.getFullYear();
    const month = now.getMonth();
    return [moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`), moment(now.getTime())];
  }
  if (type === 'year') {
    const year = now.getFullYear();
    return [moment(`${year}-01-01 00:00:00`), moment(now.getTime())];
  }
}

// 根据身份证号获取年龄
export function getAgeByIdcard(idcard: any) {
  let age = moment().year() - parseInt(idcard.substring(6, 10));
  return age;
}

// 根据身份证号获取性别
export function getSexByIdcard(idcard: any) {
  let sex = '';
  if (idcard.substr(16, 1) % 2 == 1) {
    sex = '1';
  } else {
    sex = '2';
  }
  return sex;
}

// 根据身份证号获取性别
export function checkRequestSuccess(response: any) {
  try {
    if (response.error === null || response.error.code === null) {
      return true;
    } else {
      message.error(response.error.text);
      return false;
    }
  } catch (e) {
    console.log(e);
    return false;
  }
}

// 获取cookie中的值
export function getcookie(name: string) {
  var nameEQ = name + '=';
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i].trim();
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

// 物品开柜循环物品列表根据柜子去重
export function uniqueGoodsBox(goodsList: any, open: boolean) {
  const map = new Map();
  const array = new Array();
  goodsList.map((item) => {
    if (item.resultCode !== '6000202' || open) {
      if (
        map.has(
          `${item.serviceId}-${item.cabIp}-${item.cabinetIp}-${item.cabinetNum}-${item.boxId}-${item.boxNum}`,
        )
      ) {
        // 如果有该key值
        map.set(
          `${item.serviceId}-${item.cabIp}-${item.cabinetIp}-${item.cabinetNum}-${item.boxId}-${item.boxNum}`,
          true,
        );
      } else {
        map.set(
          `${item.serviceId}-${item.cabIp}-${item.cabinetIp}-${item.cabinetNum}-${item.boxId}-${item.boxNum}`,
          false,
        ); // 如果没有该key值
        array.push(item);
      }
    }
  });
  return array;
}
